<template>
  <div class="application-form-wrapper">
    <div class="application-form">
      <h3 class="form-title">用户基本信息和空域使用信息</h3>
      
      <div class="form-grid">
        <!-- 第一行 -->
        <div class="form-cell">
          <span class="form-label">申请单位</span>
          <div class="form-value">{{ application.applicant }}</div>
        </div>
        <div class="form-cell">
          <span class="form-label">航空器型号</span>
          <div class="form-value">{{ application.aircraftModel }}</div>
        </div>
        
        <!-- 第二行 -->
        <div class="form-cell">
          <span class="form-label">申请单ID</span>
          <div class="form-value">{{ application.applicationId }}</div>
        </div>
        <div class="form-cell">
          <span class="form-label">申请时间</span>
          <div class="form-value">{{ application.applicationAcceptanceTime}}</div>
        </div>
          <!-- 第三行 -->
        <div class="form-cell">
          <span class="form-label">是否往返</span>
          <div class="form-value">{{ application.isRoundTrip ? '是' : '否' }}</div>
        </div>
        <div class="form-cell">
          <span class="form-label">任务类型</span>
          <div class="form-value">{{ application.taskType  }}</div>
        </div>

        <!-- 第四行 -->
        <div class="form-cell">
          <span class="form-label">任务开始时间</span>
          <div class="form-value">{{ formatDate(application.taskStartTime) }}</div>
        </div>
        <div class="form-cell">
          <span class="form-label">任务结束时间</span>
          <div class="form-value">{{ formatDate(application.taskEndTime) }}</div>
        </div>

        <!-- 第五行 -->
        <div class="form-cell">
          <span class="form-label">飞行频次</span>
          <div class="form-value">
            {{ application.flightFrequency || '--' }}
            <span v-if="application.flightFrequency" class="unit-text">
              ({{ application.frequencyUnit === 1 ? '次/周' : '次/天' }})
            </span>
          </div>
        </div>
        <!-- 添加空域形状显示 -->
        <div class="form-cell">
          <span class="form-label">空域形状</span>
          <div class="form-value">
            <template v-if="hasPolygonal">多边形</template>
            <template v-if="hasCircular">圆形</template>
            <template v-if="hasStraight">点线形</template>
            <template v-if="!hasPolygonal && !hasCircular && !hasStraight">--</template>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加分析结果显示区域 -->
    <div v-if="showAnalysisResults" class="analysis-results">
      <div class="analysis-item">
        <span class="analysis-label">气象状态分析</span>
        <span class="analysis-status" :class="{ 'success': weatherStatus === 'success' }">
          {{ weatherStatus === 'success' ? '成功' : '失败' }}
        </span>
      </div>
      <div class="analysis-item">
        <span class="analysis-label">空域冲突分析</span>
        <span class="analysis-status" :class="{ 'success': airspaceStatus === 'success' }">
          {{ airspaceStatus === 'success' ? '成功' : '失败' }}
        </span>
      </div>
    </div>
  
    <!-- 新增操作按钮区域 -->
    <div class="dialog-footer">
      <el-button type="primary" size="mini" @click="handleAnalyze" :loading="analyzing">分析</el-button>
      <el-button type="warning" size="mini" @click="showRejectDialog">驳回</el-button>
      <el-button type="primary" size="mini" @click="handleApprove">通过</el-button>
      <el-button type="primary" size="mini" @click="goBack">返回</el-button>
    </div>

    <!-- 驳回弹窗 -->
    <!-- <el-dialog
      title="驳回申请"
      :visible.sync="rejectDialogVisible"
      width="500px"
      @close="handleDialogClose" 
      center
    > -->
      <el-dialog
      title="驳回申请"
      :visible.sync="rejectDialogVisible"
      :modal-append-to-body="false"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="500px"

      center
    >
      <div class="reject-form">
        <div class="form-item">
          <span class="form-label">驳回理由：</span>
          <el-select 
            v-model="rejectReason" 
            placeholder="请选择驳回理由"
            style="width: 100%"
          >
            <el-option
              v-for="item in rejectReasons"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="form-item">
          <span class="form-label">调整建议：</span>
          <div class="suggestions">
            <div class="suggestion-item">
              <span>使用空域调整：</span>
              <el-input
                v-model="airspaceAdjustment"
                type="textarea"
                :rows="2"
                placeholder="请输入空域调整建议"
              />
            </div>
            <div class="suggestion-item">
              <span>使用时间调整：</span>
              <el-input
                v-model="timeAdjustment"
                type="textarea"
                :rows="2"
                placeholder="请输入时间调整建议"
              />
            </div>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确认驳回</el-button>
      </span>
    </el-dialog>
    
  </div>
</template>

<script>
import axios from 'axios'

const baseApi = process.env.NODE_ENV === 'production'
  //? process.env.VUE_APP_REMOTE_API
  ? '/api'  // 使用代理路径
  : process.env.VUE_APP_REMOTE_API_MODULE1;

export default {
  components: {
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: "默认标题"
    },
    dialogData: {
      type: Object,
      required: true
    },
    application: {
      type: Object,
      required: true,
      default: () => ({
        applicant: '',
        aircraftModel: '',
        applicationId: '',
        applicationAcceptanceTime: '',
        isRoundTrip: '',
        taskType: '',
        taskStartTime: '',              // 任务开始时间
        taskEndTime: '',                // 任务结束时间
        flightFrequency: '',            // 飞行频次
         // ... 其他字段 ...
        polygonal: "",
        circular: "",
        straight: "",
        
      })
    }
  },
  data() {
    return {
      showAnalysisResults: false,
      weatherStatus: '',
      airspaceStatus: '',
      analyzing: false, // 添加分析中状态
      addDialogVisible: false, // 控制弹窗显示与隐藏
      showAnalysisResults: false,
      weatherStatus: 'pending', // 'success'/'failed'/'pending'
      airspaceStatus: 'pending',
      rejectDialogVisible: false,
      rejectReason: '',
      airspaceAdjustment: '',
      timeAdjustment: '',
      rejectReasons: [
        { value: 'type_mismatch', label: '任务类型不符' },
        { value: 'route_conflict', label: '航线位置冲突' },
        { value: 'airspace_limit', label: '空域任务超限' }
      ]
    }
  },
  mounted() {
    console.log('dialogData132:', this.dialogData); // 在组件加载时打印dialogData
  },
  watch: {
    title: {
      immediate: true,
      handler(newVal) {
        console.log('title changed:', newVal);
        if (newVal) {
          this.fetchData(newVal);  // 调用fetchData，传入id
        }
      }
    },
  },
  computed: {
    // 判断是否有各种形状的空域
    hasPolygonal() {
      return this.application.polygonalWaypointsCoordinates && 
             this.application.polygonalWaypointsCoordinates.length > 0;
    },
    hasCircular() {
      return this.application.circleCenterCoordinates && 
             this.application.circleCenterCoordinates.length > 0;
    },
    hasStraight() {
      return this.application.straightWaypointsCoordinates && 
             this.application.straightWaypointsCoordinates.length > 0;
    }
  },
  methods: {
    // 处理分析按钮点击
    async handleAnalyze() {
      console.log('分析按钮被点击14'); // 添加调试日志
      this.analyzing = true; // 开始分析，显示加载状态
      this.showAnalysisResults = true;
      
      try {
        // TODO: 后端接口实现后替换为实际接口调用
        // const response = await axios.post(`${baseApi}/admin/airspaceDemand/analyze`, {
        //   applicationId: this.application.applicationId,
        //   // 其他需要的参数
        // });
        
        // 模拟后端返回数据
        await this.mockAnalysisResult();
      } catch (error) {
        console.error('分析请求失败:', error);
        this.$message.error('分析失败，请重试');
        this.weatherStatus = 'failed';
        this.airspaceStatus = 'failed';
      } finally {
        this.analyzing = false; // 结束分析，关闭加载状态
      }
    },

    // 模拟分析结果
    async mockAnalysisResult() {
      console.log('开始模拟分析'); // 添加调试日志
      // 模拟接口延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 随机生成分析结果
      this.weatherStatus = Math.random() > 0.5 ? 'success' : 'failed';
      this.airspaceStatus = Math.random() > 0.5 ? 'success' : 'failed';
      
      console.log('分析结果:', { 
        weather: this.weatherStatus, 
        airspace: this.airspaceStatus 
      }); // 添加调试日志
    
    },

    formatTaskTime(timeStr) {
      // 确保 timeStr 是一个有效的时间字符串
      const date = new Date(timeStr);
      console.log("拿到的时间数据初始版本", timeStr)
      // 检查是否是一个有效日期
      if (isNaN(date.getTime())) {
        return '';  // 如果日期无效，返回空字符串
      }

      // 格式化日期为 yyyy-MM-dd HH:mm:ss 格式
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');  // 补全为两位数
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    formatDate(date) {
      if (!date) return '--';
      try {
        const d = new Date(date);
        return d.toLocaleString();
      } catch (e) {
        return date; // 如果已经是格式化好的字符串就直接显示
      }
    },
    // 初始化时向后端发送请求，获取数据
    async fetchData(title) {
      try {
        // 使用 POST 请求并将 id 作为查询参数附加到 URL
        console.log("给后端发送的文件名信息", title)
        const stringTitle = title.toString()
        console.log("给后端发送的文件名string信息", stringTitle)

        const response = await axios.post(`${baseApi}/admin/airspaceDemand/getById`, null, {
          params: {
            applicationId: stringTitle
          }
        });

        // 打印从接口获取的数据
        console.log('接口返回的数据:', response.data);
        const responseData = response.data.data;
        console.log('要处理的数据:', responseData);
        // 将接口返回的数据一一对应赋值给form
        this.application = {
          applicant: response.data.data.applicantOrganization,
          applicationAcceptanceTime: response.data.data.applicationReceiveTime,
          // applicationAcceptanceTime: response.data.data.applicationAcceptanceTime,
          aircraftModel: response.data.data.aircraftModel,
          // aircraftType: response.data.data.aircraftType,
          // aircraftControlType: response.data.data.aircraftControlType,
          // maximumTakeoffWeight: response.data.data.maximumTakeoffWeight,
          // dimensionsOfAircraftInDeployedState: response.data.data.aircraftDeployedSize,
          // maximumFlightAltitude: response.data.data.maximumFlightAltitude,
          taskType: response.data.data.taskType,
          // minimumFlightAltitude: response.data.data.minimumFlightAltitude,
          taskStartTime: this.formatTaskTime(
            response.data.data.taskStartTime && response.data.data.taskStartTime.length === 5
              ? new Date(
                response.data.data.taskStartTime[0], // 年
                response.data.data.taskStartTime[1] - 1, // 月（数组中的月从0开始）
                response.data.data.taskStartTime[2], // 日
                response.data.data.taskStartTime[3], // 时
                response.data.data.taskStartTime[4]  // 分
              )
              : null
          ),
          isRoundTrip: response.data.data.isRoundTrip,
          // taskEndTime: this.formatTaskTime(response.data.data.taskEndTime),
          taskEndTime: this.formatTaskTime(
            response.data.data.taskEndTime && response.data.data.taskEndTime.length === 5
              ? new Date(
                response.data.data.taskEndTime[0], // 年
                response.data.data.taskEndTime[1] - 1, // 月（数组中的月从0开始）
                response.data.data.taskEndTime[2], // 日
                response.data.data.taskEndTime[3], // 时
                response.data.data.taskEndTime[4]  // 分
              )
              : null
          ),
          flightFrequency: response.data.data.flightFrequency,
          // takeoffLocationName: response.data.data.vertiportTOName,
          // takeoffLocationCode: response.data.data.vertiportTOCode,
          // takeoffLocationType: response.data.data.vertiportTOType,
          // takeoffLocationCoordinates: `${this.formatCoordinate(response.data.data.takeoffLocationCoordinates.longitude)}, ${this.formatCoordinate(response.data.data.takeoffLocationCoordinates.latitude)}`,
          // landingLocationName: response.data.data.vertiportLDName,
          // landingLocationCode: response.data.data.vertiportLDCode,
          // landingLocationType: response.data.data.vertiportLDType,
          // landingLocationCoordinates: `${this.formatCoordinate(response.data.data.landingLocationCoordinates.longitude)}, ${this.formatCoordinate(response.data.data.landingLocationCoordinates.latitude)}`,
          id: response.data.data.id,
          userName: response.data.data.userName,
          // applicationAcceptanceTime: response.data.data.applicationAcceptanceTime，
          applicationAcceptanceTime: response.data.data.applicationReceiveTime,
          applicationId: response.data.data.applicationId,
          approvalStatus: response.data.data.approvalStatus,
          // 添加空域形状字段
         // 添加空域形状相关的坐标数组
          polygonalWaypointsCoordinates: responseData.polygonalWaypointsCoordinates || [],
          circleCenterCoordinates: responseData.circleCenterCoordinates || [],
          straightWaypointsCoordinates: responseData.straightWaypointsCoordinates || []
          // airspaceType: response.data.data.airspaceType,
          // circularAirspace: response.data.data.circularAirspace,
          // polygonalAirspace: response.data.data.polygonalAirspace,
          // straightAirspace: response.data.data.straightAirspace,
          // circleCenterCoordinates: `${response.data.data.circleCenterCoordinates.longitude}, ${response.data.data.circleCenterCoordinates.latitude}`,
          // radius: response.data.data.radius,
        };
        console.log("空域形状数据：", {
          polygonal: this.application.polygonalWaypointsCoordinates,
          circular: this.application.circleCenterCoordinates,
          straight: this.application.straightWaypointsCoordinates
        });

        
        console.log("更新后的application", this.application);
        console.log("更新后的tableData", this.tableData);
      } catch (error) {
        console.error('请求接口时发生错误:', error);
      }
    },
    showRejectDialog() {
      console.log('驳回按钮被点击'); // 调试用
      this.rejectDialogVisible = true;
      this.rejectReason = '';
      this.airspaceAdjustment = '';
      this.timeAdjustment = '';
    },
    confirmReject() {
      if (!this.rejectReason) {
        this.$message.warning('请选择驳回理由');
        return;
      }
      
      const rejectData = {
        reason: this.rejectReason,
        airspaceAdjustment: this.airspaceAdjustment,
        timeAdjustment: this.timeAdjustment
      };
      
      this.$emit('reject', rejectData);
      this.rejectDialogVisible = false;
      this.$message.success('申请已驳回');
    },
    // handleAnalyze() {
    //   console.log('分析按钮被点击'); // 先添加这行测试
     
    // },
    handleApprove() {
      this.$emit('approve');
    },
    goBack() {
      // 使用路由导航到指定页面
      this.$router.push('airspace-need');
    },
    handleDialogClose() {
      console.log('弹窗已关闭');
      this.rejectDialogVisible = false;
    } 
  }
}
</script>

<style scoped>
.application-form-wrapper {
  position: absolute;
  right: 0;
  top: 0;
  height: 80%;
  width: auto;
  z-index: 10;
}
.application-form {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fff;
  width: 700px;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.form-title {
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  /* border-bottom: 1px solid #ebeef5; */
  color: #303133;
  font-size: 16px;
  font-weight: bold;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.form-cell {
  display: flex;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.form-label {
  padding: 10px 15px;
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  min-width: 100px;
  border-right: 1px solid #dcdfe6;
}

.form-value {
  padding: 10px 15px;
  color: #303133;
  flex-grow: 1;
  background-color: #fff;
}
.unit-text {
  color: #909399;
  font-size: 0.9em;
  margin-left: 5px;
}

.dialog-footer {
  margin-top: 20px;
  padding-top: 15px;
  /* border-top: 1px solid #eee; */
  display: flex;
  justify-content: flex-end; /* 按钮右对齐 */
  gap: 10px; /* 按钮间距 */
  position: relative;
  z-index: 1; /* 确保按钮在最上层 */
  margin-left: auto;
  align-items: center;  /* 添加此行以使按钮和分析结果垂直对齐 */
}
.el-button {
  cursor: pointer;
  pointer-events: auto;
}

.reject-form {
  padding: 0 20px;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.suggestions {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.suggestion-item {
  margin-bottom: 15px;
}

.suggestion-item:last-child {
  margin-bottom: 0;
}

.suggestion-item span {
  display: block;
  margin-bottom: 5px;
  color: #606266;
}

.dialog-footer {
  text-align: center;
}
.el-select-dropdown {
  display: block !important;
  opacity: 1 !important;
  z-index: 9999 !important;
}
/* 分析结果样式 */
/* .analysis-results {
  position: fixed;
  right: 750px; 
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.7);
  padding: 15px 20px;
  border-radius: 4px;
  z-index: 1000;
} */
.analysis-results {
  position: absolute;
  left: 300px;          /* 与分析按钮左对齐 */
  top: 550px;        /* 位于按钮下方 */
  margin-top: 10px; /* 与按钮的间距 */
  background: rgba(0, 0, 0, 0.7);
  padding: 15px 20px;
  border-radius: 4px;
  z-index: 1000;
  white-space: nowrap; /* 防止文字换行 */
}

.analysis-item {
  margin: 10px 0;
  color: white;
  display: flex;
  align-items: center;
  gap: 10px;
}

.analysis-label {
  font-size: 14px;
}

.analysis-status {
  color: #F56C6C;  /* 失败状态为红色 */
}

.analysis-status.success {
  color: #67C23A;  /* 成功状态为绿色 */
}
/* 确保按钮区域和分析结果的相对位置正确 */

</style>